package com.ali.juejin.ui.fragment.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.ali.juejin.BR
import com.ali.juejin.R
import com.ali.juejin.adapter.HomeRecommendArticleAdapter
import com.ali.juejin.adapter.HomeRecommendHotAdapter
import com.ali.juejin.base.BaseFragment
import com.ali.juejin.bean.v1.Data
import com.ali.juejin.databinding.ItemRecommendHotBinding
import com.ali.juejin.model.main.RecommendModel
import kotlinx.android.synthetic.main.fragment_home_recommend.*

class RecommendFragment: BaseFragment() {


    val model by lazy { ViewModelProvider(this).get(RecommendModel::class.java) }

    val hotAdapter by lazy { HomeRecommendHotAdapter<ItemRecommendHotBinding,Data>(context!!,BR.recommendHot) }
    val articleAdapter by lazy { HomeRecommendArticleAdapter(context!!) }

    override fun initView() {

        // 热门推荐
        recommend_hot_recycler.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        recommend_hot_recycler.adapter = hotAdapter

        // 文章
        recommend_hot_article.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        recommend_hot_article.adapter = articleAdapter

        recommend_scroll_con.setOnRefreshListener {
            model.getHomeRecommendList()
            model.getHomeRecommendHotList()
            it.finishRefresh(1000)
        }

        recommend_scroll_con.setOnLoadMoreListener {
            model.getMoreHomeRecommendList()
            it.finishLoadMore(1000)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.fragment_home_recommend,container)
    }

    override fun initData() {
        recommend_scroll_con.autoRefresh()

        model.homeRecommendList.observe(this, Observer {
            newValue->
            articleAdapter.load(newValue.data)
        })
        model.homeRecommendHotList.observe(this, Observer {
            newValue->
            hotAdapter.load(newValue.data)
        })
    }

}
